package top.kindaries.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.kindaries.device.DeviceManager;
import top.kindaries.task.Task;
import top.kindaries.task.TaskManager;

/**
 * 视频流转码推流接口
 *
 * @ClassName: ProcessController
 * @Author: zhangs
 * @Date: Created in 2021-11-01 18:13
 * @Created by IntelliJ IDEA.
 */
@RestController
@Api("视频流转码推流接口")
@RequestMapping("/process")
public class ProcessController {

    private static final Logger logger = Logger.getLogger(ProcessController.class);

    @ApiOperation("推流接口")
    @GetMapping("/{code}")
    @CrossOrigin("*")
    public String index(@PathVariable String code) {
        // 判断设备编码不为空，且在配置文件中存在相关配置
        if (StringUtils.isNotBlank(code) && DeviceManager.isContain(code)) {
            Task task;
            // 判断是否当前对应设备的转换线程
            if (TaskManager.isContain(code)) {
                // 如果有，则重新激活
                task = TaskManager.get(code);
                task.active();
            } else {
                // 如果没有，则新建
                task = TaskManager.create(DeviceManager.get(code));
            }
            if (task != null) {
                // 每次间隔1秒，循环判断m3u8文件是否创建成功
                long retryTimes = task.getDuration() * 2 / 1000;
                // 判断是否生成了转换后的m3u8文件
                String m3u8Path = task.getM3u8Path();
                try {
                    while (!FileUtil.exist(m3u8Path) && (retryTimes--) > 0) {
                        Thread.sleep(1000);
                    }
                    // 如果最终判断m3u8文件创建成功，则返回
                    if (FileUtil.exist(m3u8Path)) {
                        return FileUtil.readString(m3u8Path, "UTF-8");
                    }
                    logger.error("请求设备[" + code + "]：m3u8文件未创建");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.error("请求设备[" + code + "]：不存在");
        return null;
    }

}
